package org.luckystrophe.snowtoms;

import java.io.IOException;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;
import org.luckystrophe.snowtoms.adapter.AdapterReplies;
import org.luckystrophe.snowtoms.model.JsonRequest;
import org.luckystrophe.snowtoms.model.impl.Reply;
import org.luckystrophe.snowtoms.model.impl.RequestDeleteReply;
import org.luckystrophe.snowtoms.model.impl.RequestSendReply;
import org.luckystrophe.snowtoms.pref.UserPreference_;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockActivity;
import com.googlecode.androidannotations.annotations.AfterInject;
import com.googlecode.androidannotations.annotations.AfterViews;
import com.googlecode.androidannotations.annotations.Background;
import com.googlecode.androidannotations.annotations.Bean;
import com.googlecode.androidannotations.annotations.Click;
import com.googlecode.androidannotations.annotations.EActivity;
import com.googlecode.androidannotations.annotations.ItemClick;
import com.googlecode.androidannotations.annotations.UiThread;
import com.googlecode.androidannotations.annotations.ViewById;
import com.googlecode.androidannotations.annotations.res.StringRes;
import com.googlecode.androidannotations.annotations.sharedpreferences.Pref;

@EActivity(R.layout.activity_reply)
public class ReplyActivity extends SherlockActivity implements TextWatcher {

	@ViewById(R.id.lv_reply)
	ListView listviewReply;

	@Bean
	AdapterReplies replyAdapter;

	@ViewById(R.id.et_replyComment)
	EditText et_replyComment;

	@ViewById(R.id.tv_noReply)
	TextView tv_noReply;

	@StringRes(R.string.pleaseWait)
	String pleaseWait;

	@ViewById(R.id.btn_sendReply)
	Button btn_sendReply;

	@Bean(RequestSendReply.class)
	JsonRequest sendReplyRequest;

	@Bean(RequestDeleteReply.class)
	JsonRequest requestDeleteReply;

	@Pref
	UserPreference_ pref;

	private ProgressDialog mProgressDialog;

	private long msgId;

	@AfterInject
	public void afterInject() {
		Intent getIntent = getIntent();
		if (!getIntent.hasExtra("msgId")) {
			return;
		}
		msgId = getIntent.getLongExtra("msgId", 0L);
		replyAdapter.setMsgid(msgId);
	}

	@AfterViews
	public void afterViews() {
		listviewReply.setAdapter(replyAdapter);
		et_replyComment.addTextChangedListener(this);
	}

	@Click(R.id.btn_sendReply)
	public void clickSendReply() {

		if (mProgressDialog != null && mProgressDialog.isShowing()) {
			return;
		}

		if (pref.usrId().get() == 0L) {
			Toast.makeText(this, "페이스북으로 로그인 후에 이용하실 수 있습니다.", Toast.LENGTH_SHORT).show();
			return;
		}

		mProgressDialog = ProgressDialog.show(this, "", pleaseWait, true);
		String comment = et_replyComment.getText().toString();
		if (comment.length() == 0) {
			return;
		}

		et_replyComment.setText("");
		sendWriteReply(comment);
	}

	@Background
	public void sendWriteReply(String comment) {
		((RequestSendReply) sendReplyRequest).setWriteReplyParams(msgId, comment);
		JSONObject resultJo = new JSONObject();
		try {
			resultJo = sendReplyRequest.sendJsonRequest();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		afterSendWriteReply(resultJo);
	}

	@UiThread
	public void afterSendWriteReply(JSONObject resultJo) {

		if (mProgressDialog != null && mProgressDialog.isShowing()) {
			mProgressDialog.dismiss();
		}

		int resultCode = 0;

		try {
			resultCode = resultJo.getInt("resultCode");
		} catch (JSONException e) {
			e.printStackTrace();
		}

		if (resultCode == 1) {
			replyAdapter.getReplies(msgId);
			setResult(RESULT_OK);
		}
	}

	public void setNoreplyText(int visible) {
		tv_noReply.setVisibility(visible);
	}

	@Override
	public void afterTextChanged(Editable s) {
		// TODO Auto-generated method stub

	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count, int after) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		// TODO Auto-generated method stub
		btn_sendReply.setEnabled(s.length() > 0);
	}

	@ItemClick(R.id.lv_reply)
	public void clickReplyList(Reply selectedReply) {
		clickOptionMenu(selectedReply);
	}

	public void clickOptionMenu(Reply selectedReply) {
		if (selectedReply.getUsrId() != pref.usrId().get()) {
			return;
		}

		final long selectedMsgId = selectedReply.getMsgId();
		final long selectedReplyId = selectedReply.getReplyId();

		final CharSequence[] items = { "댓글 삭제" };

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setItems(items, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int item) {
				if (item == 0) {
					showDeleteMessageDialog(selectedMsgId, selectedReplyId);
				}
			}
		});
		AlertDialog alert = builder.create();

		alert.show();
	}

	private void showDeleteMessageDialog(final long msgId, final long replyId) {
		AlertDialog.Builder alert_confirm = new AlertDialog.Builder(this);
		alert_confirm.setMessage("댓글를 삭제하시겠습니까?").setPositiveButton("확인", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				deleteReply(msgId, replyId);
			}
		}).setNegativeButton("취소", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				return;
			}
		});
		AlertDialog alert = alert_confirm.create();
		alert.show();
	}

	@Background
	public void deleteReply(long msgId, long replyId) {
		int resultCode = 0;
		try {
			((RequestDeleteReply) requestDeleteReply).setMsgId(msgId);
			((RequestDeleteReply) requestDeleteReply).setReplyId(replyId);
			JSONObject jo = requestDeleteReply.sendJsonRequest();
			resultCode = jo.getInt("resultCode");
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			afterDeleteMessage(resultCode, msgId);
		}
	}

	@UiThread
	public void afterDeleteMessage(int resultCode, long msgId) {
		if (resultCode == 1) {
			replyAdapter.getReplies(msgId);
			setResult(RESULT_OK);
		} else {
			Toast.makeText(this, "에러가 발생했습니다.", Toast.LENGTH_SHORT).show();
		}
	}

}
